<template>
  <RouterView></RouterView>
</template>

<script>
//import { Splitpanes, Pane } from 'splitpanes';
import { onMounted, onUnmounted, ref } from 'vue';
import mqttService from '../util/mqttService';
import { useRouter } from 'vue-router';
//import Paho from 'paho-mqtt';
import axios from "../axios/axios"
export default {
  name: 'IndexView',
  components: {
    //Splitpanes,
    //Pane,
  },

  setup() {
    const userId = ref("");
    const ifOptions = ref("")
    const params = ref("")
    const router = useRouter();
    // const iframeSrc = computed(() => {
    //   const urlLast = getUrl(params.value.targetPageId)
    //   useRouter.push(`/${urlLast}?${ifOptions.value}`); 
    //   return ""
    // });
    const putUrl = async () => {
      router.push({ path: '/register' });
    }
    const JSONbig = require('json-bigint');
    let isConnected = false;
    const reconnectInterval = 3000;
    const maxReconnectAttempts = 10;
    let reconnectAttempts = 0;
    const isRenZeng = ref(false)
    const trainingId = ref("")
    async function getUrl(type, nowTrainingId) {
      if (!isRenZeng.value || trainingId.value != nowTrainingId) {
        const infoStr = localStorage.getItem('IRAInfo');
        if (!infoStr) {
          return "accessKey"; // info不存在时返回
        }
        const info = JSONbig.parse(infoStr);
        if (info) {
          try {
            // 等待axios请求完成（用await处理异步）
            const res = await axios.get("/train/select?userId=" + String(info.userId))
            if (res.data.Data.accesskey != null && res.data.Data.accesskey != "") {
              localStorage.removeItem("X-Access-Key");
              localStorage.setItem('X-Access-Key', res.data.Data.accesskey);
              isRenZeng.value = true
              trainingId.value = res.data.Data.trainingid
              // 返回switchUrl的结果
              return switchUrl(type);
            } else {
              return "accessKey";
            }
          } catch (error) {
            // 处理请求失败的情况
            console.error("请求失败:", error);
            return "accessKey"; // 或其他默认值
          }
        } else {
          return "accessKey";
        }
      }

      // 当isRenZeng.value为true时的默认返回
      return switchUrl(type);
    }
    const switchUrl = (type) => {
      switch (type) {
        case "ProductRegister":
          return "register"
        case "CodeRule":
          return "rules"
        case "CodeRecord":
          return "records"
        case "ProductInfo":
          return "info"
        case "PutStore":
          return "putstore"
        case "ProcessRegister":
          return "pcb/etchregister"
        case "ProductState":
          return "pcb/productstate"

        case "applySave":
          return "hotel/apply"
        case "tvSelect":
          return "hotel/tv"
        case "orderSave":
          return "hotel/order"
        case "orderPrint":
          return "hotel/print"
        case "payMent":
          return "hotel/payment"
        case "supplierInfo":
          return "hotel/print"
        case "confirmOrder":
          return "tv/confirmOrder"
        case "printOrder":
          return "tv/confirmOrder"
        case "fileOrder":
          return "tv/confirmOrder"
        case "makeContract":
          return "tv/makeContract"
        case "sendContract":
          return "tv/makeContract"
        case "producePlan":
          return "tv/producePlan"
        case "transmitPeople":
          return "tv/producteInfo"
        case "produceInfo":
          return "tv/producteInfo"
        case "materialPlan":
          return "tv/materialPlan"
        case "transferPurchase":
          return "tv/materialPlan"
        case "lcdSelect":
          return "tv/lcdSelect"
        case "partOrder":
          return "tv/partOrder"
        case "partOrderPrint":
          return "hotel/print"
        case "filePartOrder":
          return "tv/partFileOrder"
        case "showOrder":
          return "lcd/showOrder"
        case "logisticsOrder":
          return "lcd/logisticsOrder"
        case "logisticsOrderInfo":
          return "lcd/logisticsOrderInfo"
        case "transmitManage":
          return "lcd/logisticsOrderInfo"
        case "makeDelivery":
          return "lcd/logisticsOrderInfo"
        case "transmitDriver":
          return "lcd/logisticsOrderInfo"
        case "packageInfo":
          return "lcd/packageInfo"
        case "vehicleDispatch":
          return "logistics/vehicleDispatch"
        case "vehicleDispatchInfo":
          return "logistics/vehicleDispatchInfo"
        case "infoReport":
          return "logistics/infoReport"
        case "checkOrder":
          return "lcd/logisticsOrderInfo"
        case "checkPack":
          return "logistics/checkPack"
        case "goodsDeliver":
          return "lcd/logisticsOrderInfo"
        case "checkGoods":
          return "tv/partFileOrder"
        case "takeOver":
          return "logistics/takeOver"
        case "partStore":
          return "lcd/partStore"
        case "monthBill":
          return "lcd/monthBill"
        case "monthBillCheck":
          return "lcd/monthBill"
        case "payMentPart":
          return "hotel/payment"
        case "materialDemand":
          return "hotel/materialDemand"
        case "materialDemandInfo":
          return "hotel/materialDemand"
        case "materialReceive":
          return "hotel/materialDemand"
        case "tvAssembly":
          return "hotel/tvAssembly"
        case "tvComplete":
          return "hotel/tvComplete"
        case "tvStore":
          return "tv/tvStore"
        case "tvLogisticsOrder":
          return "lcd/logisticsOrder"
        case "tvLogisticsOrderInfo":
          return "lcd/logisticsOrderInfo"
        case "outBound":
          return "tv/outBound"
        case "checkLogistics":
          return "lcd/logisticsOrderInfo"
        case "checkPackageInfo":
          return "logistics/checkPack"
        case "userStore":
          return "tv/userStore"
        case "deliveryConfirm":
          return "lcd/deliveryconfirm"
        default:
          return "defaultView"
      }
    }

    function onConnect(userId) {
      console.log('Connected to MQTT broker');
      reconnectAttempts = 0
      mqttService.onsubscribe('SyncPage/+/' + userId);
      mqttService.onsubscribe('SendCode/+/' + userId);
      mqttService.onsubscribe('ResetStep/+/' + userId);

      console.log('SyncPage/+/' + userId);

    }

    function onFailure(message) {
      console.log('Failed to connect to MQTT broker:', message.errorMessage);
    }
    function onConnectionLost(responseObject) {
      if (responseObject.errorCode !== 0) {
        isConnected = false;
        console.log('连接断开，错误信息: ', responseObject.errorMessage);
        if (reconnectAttempts < maxReconnectAttempts) {
          console.log(`尝试重连 (第${reconnectAttempts + 1}次)...`);
          setTimeout(() => {
            cn(userId.value);
            reconnectAttempts++;
          }, reconnectInterval);
        } else {
          console.log('达到最大重连次数，放弃重连');
        }
      }
    }
    async function onMessageArrived(message) {
      //console.log("message:", message.payloadString);
      // 你可以在这里处理接收到的消息，例如将其存储在 Vuex 或 Vue 3 的响应式状态中
      var mesList = message.topic.split("/")
      if (mesList[0] === "SyncPage" && mesList[2] === userId.value) {
        const jsonObject = JSONbig.parse(message.payloadString);
        params.value = jsonObject
        var info = ""
        info = "AppId=" + mesList[1] + "&targetPageId=" + jsonObject.targetPageId + "&trainingId=" + jsonObject.trainingId
          + "&isDisable=" + jsonObject.isDisable + "&userId=" + userId.value
        if (jsonObject.productType != undefined) {
          info = info + "&productType=" + jsonObject.productType
        }
        if (jsonObject.productInfoId != undefined) {
          info = info + "&productInfoId=" + jsonObject.productInfoId
        }
        if (jsonObject.data != undefined) {
          info = info + "&code=" + jsonObject.data
        }
        ifOptions.value = info
        const urlLast = await getUrl(jsonObject.targetPageId, jsonObject.trainingId)
        //console.log("1111:", `/${urlLast}?${ifOptions.value}`);
        router.push('/defaultView');
        setTimeout(() => {
          router.push(`/${urlLast}?${ifOptions.value}`);
        }, 10);
      } else if (mesList[0] === "SendCode" && mesList[2] === userId.value) {
        const jsonObject = JSONbig.parse(message.payloadString);
        // ifOptions.value = "AppId=" + mesList[1] + "&targetPageId=" + params.value.targetPageId + "&trainingId="
        //   + jsonObject.trainingId + "&isDisable=" + params.value.isDisable + "&userId=" + userId.value + "&code=" + jsonObject.data
        var a1 = ifOptions.value
        const urlSearchParams = new URLSearchParams(a1);

        // 判断并设置/替换surplus参数值
        if (urlSearchParams.has('data')) {
          urlSearchParams.set('code', jsonObject.data);
        } else {
          urlSearchParams.append('code', jsonObject.data);
        }
        const newUrlParamsStr = urlSearchParams.toString();
        ifOptions.value = newUrlParamsStr
        const urlLast = await getUrl(params.value.targetPageId, jsonObject.trainingId)
        //console.log("2222:", `/${urlLast}?${ifOptions.value}`, params.value.targetPageId);
        router.push('/defaultView');
        setTimeout(() => {
          router.push(`/${urlLast}?${ifOptions.value}`);
        }, 10);
      } else if (mesList[0] === "ResetStep" && mesList[2] === userId.value) {
        const jsonObject = JSONbig.parse(message.payloadString);
        var data = { ...params.value }
        data.targetPageId = jsonObject.targetPageId
        params.value = data
        ifOptions.value = "AppId=" + mesList[1] + "&targetPageId=" + jsonObject.targetPageId + "&trainingId=" + jsonObject.trainingId
          + "&isDisable=false" + "&userId=" + userId.value + "&reset"
        const urlLast = await getUrl(jsonObject.targetPageId, jsonObject.trainingId)
        //console.log("3333:", `/${urlLast}?${ifOptions.value}`);
        router.push('/defaultView');
        setTimeout(() => {
          router.push(`/${urlLast}?${ifOptions.value}`);
        }, 10);
      } else if (mesList[0] === "SendState" && mesList[2] === userId.value) {
        const jsonObject = JSONbig.parse(message.payloadString);
        var a = ifOptions.value
        const urlSearchParams = new URLSearchParams(a);
        // 判断并设置/替换surplus参数值
        if (urlSearchParams.has('surplus')) {
          urlSearchParams.set('surplus', jsonObject.surplus);
        } else {
          urlSearchParams.append('surplus', jsonObject.surplus);
        }
        // 判断并设置/替换state参数值
        if (urlSearchParams.has('state')) {
          urlSearchParams.set('state', jsonObject.state);
        } else {
          urlSearchParams.append('state', jsonObject.state);
        }
        // 获取最终修改后的参数部分字符串
        const newUrlParamsStr = urlSearchParams.toString();
        ifOptions.value = newUrlParamsStr
        const urlLast = await getUrl(params.value.targetPageId, jsonObject.trainingId)
        //console.log("2222:", `/${urlLast}?${ifOptions.value}`, params.value.targetPageId);
        router.push('/defaultView');
        setTimeout(() => {
          router.push(`/${urlLast}?${ifOptions.value}`);
        }, 10);
      }
    }
    function cn(userid) {
      //console.log(isConnected,mqttService.client);
      if (isConnected) return;
      // 你可以在这里添加任何需要在组件挂载时执行的代码  
      mqttService.onconnect({
        onSuccess: function () {
          onConnect(userid);
        },
        onFailure: onFailure,
        timeout: 3,
      })
      mqttService.client.onConnectionLost = onConnectionLost;
      mqttService.onMessage(onMessageArrived)
    }
    onMounted(() => {
      // 你可以在这里添加任何需要在组件挂载时执行的代码  
      //localStorage.removeItem("X-Access-Key");
      const param = new URLSearchParams(window.location.search);
      params.value = param
      //userId.value = param.get('token')
      //localStorage.setItem('IRAInfo',param.get('token'))
      var url = param.get('user_api')
      var token = param.get('token')
      var clientid = param.get('clientid')
      var info = localStorage.getItem('IRAInfo')
      var info_token = localStorage.getItem('IRAInfo_token')

      // console.log("info:", info);
      // console.log("info_token:", info_token);
      if (info_token == null || info == null) {
        axios.get(url, {
          headers: {
            'Authorization': "Bearer " + token,
            'clientid': clientid
          }
        }).then(res => {
          localStorage.setItem('IRAInfo', JSON.stringify(res.data.data))
          localStorage.setItem('IRAInfo_token', token)
          userId.value = (String)(res.data.data.userId)
          cn((String)(res.data.data.userId))
        })
      } else {
        if (info_token != token && token != null) {
          axios.get(url, {
            headers: {
              'Authorization': "Bearer " + token,
              'clientid': clientid
            }
          }).then(res => {
            localStorage.setItem('IRAInfo', JSON.stringify(res.data.data))
            localStorage.setItem('IRAInfo_token', token)
            userId.value = (String)(res.data.data.userId)
            cn((String)(res.data.data.userId))
          })
        } else {
          userId.value = (String)(JSONbig.parse(info).userId)
          cn((String)(JSONbig.parse(info).userId))
        }
      }
    });
    onUnmounted(() => {
      // 你可以在这里添加任何需要在组件卸载时执行的代码，例如断开 MQTT 连接  
      mqttService.onDisconnect();
    });
    return {
      ifOptions,
      putUrl
    };
  },
  methods: {
    onResizeStart() {
      this.iframeContainerStyle.pointerEvents = 'none';
    },
    onResizeEnd() {
      this.iframeContainerStyle.pointerEvents = 'auto';
    }
  },
  data() {
    return {
      iframeContainerStyle: {
        width: '100%',
        height: '100%',
        pointerEvents: 'auto'
      },

    };
  },
};
</script>

<style>
.splitpanes__pane {
  display: flex;
  /* justify-content: center;
  align-items: center; */
  /* background-color: skyblue; */
  height: 100vh;
}

.splitpanes {
  position: relative;
}

.splitpanes.default-theme .splitpanes__pane {
  background-color: white;
}
</style>
